<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * RMB处理控制器
 * @author [Eason] <[eason_1988@qq.com]>
 * @date(2016-03-31)
 */
class Cny extends CI_Controller {
	private $user_info;
	private $object = 'cny';

	public function __construct(){  
        parent::__construct();
        $this->load->library('passPort');
        $this->passportClass = $this->passport;
        
        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
		$this->user_info = $this->passportClass->checkCookieAuthCode('','',true);
    }

	//充值页面
	public function deposit(){
		if(empty($this->user_info)){
			redirect("/");
		}
		$this->load->library('CI_Wechat');
		$rs = $this->ci_wechat->getJsTicket();
		
		$this->load->config('wxpay_config');
		$timeStamp = time();
		$jsSign = $this->ci_wechat->getJsSign($this->config->item('jsurl'),$timeStamp);
		$assign['user_info'] = $this->user_info;
		$assign['appId'] = $this->config->item('appid');
		$assign['timeStamp'] = $timeStamp;
		$assign['nonceStr'] = $jsSign['nonceStr'];
		$assign['signature'] = $jsSign['signature'];
		$assign['jsApiList'] = "'checkJsApi','chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage'";
		// $url = $this->ci_wechat->getShortUrl("http://mp.weixin.qq.com/s?__biz=MzAxMzg4NjA0OQ==&mid=2247483655&idx=1&sn=4dbaefed671951a22483b223b7bed1ed");
		$assign['shareUrl'] = $this->ci_wechat->getOauthRedirect('https://720quan.com/cny/callback?uid='.$this->user_info['uid'],'ad230wkdnm2f985jdf93jr');
        $this->load->view('cny/deposit',$assign);
	}


	//提现页面
	public function withdraw(){
		if(empty($this->user_info)){
			redirect("/");
		}
		$this->load->config('cny');
		$get = $this->input->get();
		$assign['user_info'] = $this->user_info;
		$assign['bankArr'] = $this->config->item('bankArr');

		$where = array(
			'uid' => $this->user_info['uid'],
		);
		$this->load->model('cny_model');
		$cnyShare = $this->cny_model->getCnyShare($where,1);
		$assign['freeNum'] = isset($cnyShare['num'])?$cnyShare['num']:0;

		$this->load->library('Bank');
		$assign['bank'] = $this->bank->getBank($this->user_info['uid']);
        $this->load->view('cny/withdraw',$assign);
	}


	public function records(){
		if(empty($this->user_info)){
			redirect("/");
		}
		$uid = $this->user_info['uid'];
		$this->load->model('user_model');
		$records = $this->user_model->getObjectLog($this->object,$uid);
		$assign['title'] = '账户明细';
		$assign['records'] = $records;
		$assign['desc'] = $this->config->item('desc');
		$assign['sources'] = $this->config->item('sources');
	 	$this->load->view('cny/records',$assign);

	}

	public function callback(){
		$get = $this->input->get();
		writeDebug('['.date('Y-m-d H:i:s').'] get='.var_export($get,true), "cny_callback");
		$status = $get['status'];
		$type = ($get['action']=='onMenuShareTimeline')?1:0;
		if(empty($this->user_info)){
			writeDebug('['.date('Y-m-d H:i:s').'] 登陆失效', "cny_callback");
			die;
		}
		$datetime = date('Y-m-d H:i:s');
		if($status=='success'){
			$this->load->model('cny_model');
			$where = array(
				'uid' => $this->user_info['uid'],
			);
			$tmpData = $this->cny_model->getCnyShare($where,1);
			if(empty($tmpData)){
				$inArr = array(
					'uid' => $this->user_info['uid'],
					'num' => 1,
					'total' => 1,
					'type' => $type,
					'lastest_modify' => $datetime,
				);
				$this->cny_model->addCnyShare($inArr);
			}else{
				$where = array(
					'uid' => $this->user_info['uid'],
				);
				$upArr = array(
					'num' => 1,
					'total' => $tmpData['total']+1,
					'lastest_modify' => $datetime,
				);
				if($type==1){
					$upArr['type'] = 1;
				}
				$this->cny_model->updateCnyShare($upArr,$where);
			}
		}

	}

	public function wxDeposit(){
		if(empty($this->user_info)){
			jsonReturn(-1,'请重新登陆');
		}
		$this->load->config('cny');
        $cnySTOP = $this->config->item('cnySTOP');
        if($cnySTOP==1){
        	jsonReturn(-1,'暂未开放');
        }
		$post = $this->input->post();
		$amount = trim($post['amount']);
		if($amount<20){
			jsonReturn(-1,'充值金额不能少于20元');
		}
		$this->load->library('CI_Wechat');
		$this->load->config('wxpay_config');
		// var_dump($jsSign);
		$wxconfig['appid'] = $this->config->item('appid');
		$wxconfig['mch_id'] = $this->config->item('mch_id');
		$wxconfig['apikey'] = $this->config->item('apikey');
		$wxconfig['appsecret'] = $this->config->item('appsecret');
		$wxconfig['sslcertPath'] = $this->config->item('sslcertPath');
		$wxconfig['sslkeyPath'] = $this->config->item('sslkeyPath');
		//由于此类库构造函数需要传参，我们初始化类库就传参数给他吧
		$this->load->library('WechatPay',$wxconfig);

		$ip = get_ip();
		$datetime = date('Y-m-d H:i:s');
		$this->load->library('Order');
		$orderData = array(
			'recharge_type' => 1,//1微信，2gopay
			'uid' => $this->user_info['uid'],
			'openid' => $this->user_info['openid'],
			'amount' => $amount,
			'ip' => $ip,
			'create_time' => $datetime,
			'lastest_modify' => $datetime,
		);
		$out_trade_no = $this->order->createOrder($orderData,'wx');
		if(!$out_trade_no){
			jsonReturn(-1,'充值提交失败');
		}
		
		$notify_url = $this->config->item('notify_url');
		$device_info = $this->config->item('device_info');
		$total_fee = bcmul($amount,100,0);
		$openid = $this->user_info['openid'];
		// echo 'test'.",".$out_trade_no.",".$total_fee.",".$notify_url.",".$openid;
		$prepay_id = $this->wechatpay->getPrepayId('test',$out_trade_no,$total_fee,$notify_url,$openid);
		// var_dump($prepay_id);
		$timeStamp = time();
		$nonceStr = $this->ci_wechat->generateNonceStr();
		// $assign['user_info'] = $this->user_info;
		$assign['appId'] = $wxconfig['appid'];
		$assign['timeStamp'] = $timeStamp;
		$assign['nonceStr'] = $nonceStr;
		$assign['package'] = 'prepay_id='.$prepay_id;
		//支付签名
		$signArr = array(
			'appId' => $wxconfig['appid'],
			'timeStamp' => $timeStamp,//S必须大写
			'nonceStr' => $nonceStr,
			'package' => 'prepay_id='.$prepay_id,
			'signType' => 'MD5',
		);
		$assign['paySign'] = $this->wechatpay->sign($signArr);
		jsonReturn(0,'success',$assign);
	}

	public function depositCallBack(){
		$datetime = date('Y-m-d H:i:s');
		$this->load->config('wxpay_config');
		$wxconfig['appid'] = $this->config->item('appid');
		$wxconfig['mch_id'] = $this->config->item('mch_id');
		$wxconfig['apikey'] = $this->config->item('apikey');
		$wxconfig['appsecret'] = $this->config->item('appsecret');
		$wxconfig['sslcertPath'] = $this->config->item('sslcertPath');
		$wxconfig['sslkeyPath'] = $this->config->item('sslkeyPath');
		//由于此类库构造函数需要传参，我们初始化类库就传参数给他吧
		$this->load->library('WechatPay',$wxconfig);
		$callbackData = $this->wechatpay->get_back_data();
		if($callbackData==null){
			$this->wechatpay->response_back("FAIL", 'Invalid validate['.__LINE__.']');
			die;
		}
		if($wxconfig['appid']!=$callbackData['appid']){
			$this->wechatpay->response_back("FAIL", 'Invalid appid['.__LINE__.']');
			die;
		}
		if($wxconfig['mch_id']!=$callbackData['mch_id']){
			$this->wechatpay->response_back("FAIL", 'Invalid mch_id['.__LINE__.']');
			die;
		}
		if('CNY'!=$callbackData['fee_type']){
			$this->wechatpay->response_back("FAIL", 'Invalid fee_type['.__LINE__.']');
			die;
		}
		if('Y'!=$callbackData['is_subscribe']){
			$this->wechatpay->response_back("FAIL", 'Invalid is_subscribe['.__LINE__.']');
			die;
		}
		if('JSAPI'!=$callbackData['trade_type']){
			$this->wechatpay->response_back("FAIL", 'Invalid trade_type['.__LINE__.']');
			die;
		}
		$this->load->library('Order');
		$orderData = $this->order->getOrder($callbackData['out_trade_no']);
		if(empty($orderData)){
			$this->wechatpay->response_back("FAIL", 'Invalid orderno['.__LINE__.']');
			die;
		}
		if($orderData['openid']!=$callbackData['openid']){
			$this->wechatpay->response_back("FAIL", 'Invalid openid['.__LINE__.']');
			die;
		}
		$total_fee = $callbackData['total_fee'];//订单总金额，单位为分
		$tmpAmount = bcmul($orderData['amount'],100,0);
		if($total_fee!=$tmpAmount){
			$this->wechatpay->response_back("FAIL", 'Invalid amount['.__LINE__.']');
			die;
		}
		if($orderData['send_status']==1){
			$this->wechatpay->response_back("SUCCESS", '已经发送['.__LINE__.']');
			die;
		}

		if($callbackData['result_code']=='SUCCESS'){
			// $this->wechatpay->response_back("SUCCESS", '支付成功');
			$time_end = $callbackData['time_end'];//完成支付时间
			$transaction_id = $callbackData['transaction_id'];//微信支付订单号
			//更新订单
			$upArr = array(
				'bank_type' => $callbackData['bank_type'],
				'pay_status' => 1,
				'pay_time' => date('Y-m-d H:i:s',strtotime($time_end)),
				'return_code' => $callbackData['result_code'],
				'return_transaction_id' => $transaction_id,
				'return_mch_id' => $callbackData['mch_id'],
				'lastest_modify' => $datetime
			);
			$where = array('orderno'=>$callbackData['out_trade_no']);
			$rs = $this->order->updateOrder($upArr,$where);
			if($rs){
				// if($orderData['uid']>100496 && $orderData['amount']>=200){
				// 	$this->load->library('Referrals');
				// 	$flag = $this->referrals->getInviteBySlave($orderData['uid']);
				// 	if(!$flag){
				// 		$this->referrals->addInvite($orderData['uid']);
				// 	}
				// }
				//链接redis
		        $this->load->driver('cache');
		        $this->cache->redis->is_supported();
		        $redis= $this->cache->redis->getClient();
				try {
					$redis->multi();
					$try  = 2; // 推两次都不行就不推了……
					do {
						$len = $redis->lPush('LIST_DEPOSIT', $callbackData['out_trade_no']);
						if ($len != false) break;
						--$try;
					} while($try > 0);
					if ($len == false) throw new Exception('L:'.__LINE__.' 队列推送失败!', 1);
					$redis->exec();
					$this->wechatpay->response_back("SUCCESS", '已经放入队列['.$callbackData['out_trade_no'].']');
				} catch (Exception $e) {
					$redis->discard();
					writeDebug('['.$datetime.'] Err:'.$e->getMessage(),'CNY');
					$this->wechatpay->response_back("FAIL", '放入队列失败-回滚['.$callbackData['out_trade_no'].']');
				}
			}else{
				writeDebug('['.$datetime.'] updateOrder Error['.$callbackData['out_trade_no'].']'.var_export($upArr,true), "CNY");
			}

		}else{//支付失败
			$this->wechatpay->response_back("FAIL", $callbackData['err_code_des']."[".$callbackData['err_code']."]");
			die;
		}
	}


	public function bankDepositCallBack(){
		$post = $this->input->post();
		$datetime = date('Y-m-d H:i:s');
		/*
  'feeAmt' => '0.1',
  'respCode' => '0000',
  'signType' => '1',
  'buyerContact' => '020-88888888',
  'version' => '2.1',
  'merOrderNum' => 'O201605261038559448',
  'tranFinishTime' => '20160526104243',
  'goodsDetail' => 'productDesc',
  'msgExt' => '',
  'orderId' => '2016052653113599',
  'tranAmt' => '20',
  'merchantID' => '0000026631',
  'charset' => '2',
  'tranIP' => '113.109.164.154',
  'signValue' => '3ed58df7e35053106ad8eee363c7a238',
  'buyerName' => 'MWEB',
  'tranDateTime' => '20160526103855',
  'bankCode' => 'CMB',
  'authID' => '',
  'merRemark2' => '',
  'tranCode' => '8888',
  'gopayOutOrderId' => '1653113599',
  'backgroundMerUrl' => 'https://720quan.com/cny/bankDepositCallBack',
  'merRemark1' => '',
  'frontMerUrl' => 'https://720quan.com/user',
  'language' => '1',
  'goodsName' => 'product',
)
		*/
		$this->load->config('gopay_config');
		writeDebug('['.$datetime.'] post='.var_export($post,true), "bankDepositCallBack");
		$version = $post["version"];
		$charset = $post["charset"];
		$language = $post["language"];
		$signType = $post["signType"];
		$tranCode = $post["tranCode"];
		$merchantID = $post["merchantID"];
		$merOrderNum = $post["merOrderNum"];
		$tranAmt = $post["tranAmt"];
		$feeAmt = $post["feeAmt"];
		$frontMerUrl = $post["frontMerUrl"];
		$backgroundMerUrl = $post["backgroundMerUrl"];
		$tranDateTime = $post["tranDateTime"];
		$tranIP = $post["tranIP"];
		$respCode = $post["respCode"];
		$msgExt = $post["msgExt"];
		$orderId = $post["orderId"];
		$gopayOutOrderId = $post["gopayOutOrderId"];
		$bankCode = $post["bankCode"];
		$tranFinishTime = $post["tranFinishTime"];
		$merRemark2 = $post["merRemark2"];
		$merRemark1 = $post["merRemark1"];
		$buyerName = $post["buyerName"];
		$signValue = $post["signValue"];
		$VerficationCode = '520520520123';     
		if($version != $this->config->item('version')){
			writeDebug('['.$datetime.'] version 错误['.$version.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($charset != $this->config->item('charset')){
			writeDebug('['.$datetime.'] charset 错误['.$charset.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($language != $this->config->item('language')){
			writeDebug('['.$datetime.'] language 错误['.$language.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($signType != $this->config->item('signType')){
			writeDebug('['.$datetime.'] signType 错误['.$signType.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($tranCode != $this->config->item('tranCode')){
			writeDebug('['.$datetime.'] tranCode 错误['.$tranCode.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($merchantID != $this->config->item('merchantID')){
			writeDebug('['.$datetime.'] merchantID 错误['.$merchantID.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}
		if($buyerName != $this->config->item('buyerName')){
			writeDebug('['.$datetime.'] buyerName 错误['.$buyerName.']', "CNY");
			die('RespCode=9999|JumpURL=');
		}

		//注意md5加密串需要重新拼装加密后，与获取到的密文串进行验签
		$signValue2='version=['.$version.']tranCode=['.$tranCode.']merchantID=['.$merchantID.']merOrderNum=['.$merOrderNum.']tranAmt=['.$tranAmt.']feeAmt=['.$feeAmt.']tranDateTime=['.$tranDateTime.']frontMerUrl=['.$frontMerUrl.']backgroundMerUrl=['.$backgroundMerUrl.']orderId=['.$orderId.']gopayOutOrderId=['.$gopayOutOrderId.']tranIP=['.$tranIP.']respCode=['.$respCode.']gopayServerTime=[]VerficationCode=['.$VerficationCode.']';
		//VerficationCode是商户识别码为用户重要信息请妥善保存
		//注意调试生产环境时需要修改这个值为生产参数
		$signValue2 = md5($signValue2);
		if($signValue==$signValue2){
			if($respCode=='0000'){
				//验签成功
				$this->load->library('Order');
				$orderData = $this->order->getOrder($merOrderNum);
				if(empty($orderData)){
					writeDebug('['.$datetime.'] 无效订单 Error['.$merOrderNum.']', "CNY");
					die('RespCode=9999|JumpURL=');
				}
				if($orderData['amount']!=$tranAmt){
					writeDebug('['.$datetime.'] 订单金额错误 Error['.$tranAmt.']', "CNY");
					die('RespCode=9999|JumpURL=');
				}
				//更新订单
				$upArr = array(
					'bank_type' => $bankCode,
					'pay_status' => 1,
					'pay_time' => date('Y-m-d H:i:s',strtotime($tranFinishTime)),
					'return_code' => $respCode,
					'return_transaction_id' => $orderId,
					'return_mch_id' => $merchantID,
					'lastest_modify' => $datetime
				);
				$where = array('orderno'=>$merOrderNum);
				$rs = $this->order->updateOrder($upArr,$where);
				if($rs){
					//链接redis
			        $this->load->driver('cache');
			        $this->cache->redis->is_supported();
			        $redis= $this->cache->redis->getClient();
					try {
						$redis->multi();
						$try  = 2; // 推两次都不行就不推了……
						do {
							$len = $redis->lPush('LIST_DEPOSIT', $merOrderNum);
							if ($len != false) break;
							--$try;
						} while($try > 0);
						if ($len == false) throw new Exception('L:'.__LINE__.' 队列推送失败!', 1);
						$redis->exec();
						writeDebug('['.$datetime.'] 充值成功['.$tranAmt.']', "CNY");
						die('RespCode=0000|JumpURL=https://720quan.com/user'); 
					} catch (Exception $e) {
						$redis->discard();
						writeDebug('['.$datetime.'] Err:'.$e->getMessage(),'CNY');
						die('RespCode=9999|JumpURL=');
					}
				}else{
					writeDebug('['.$datetime.'] updateOrder Error['.$merOrderNum.']', "CNY");
					die('RespCode=9999|JumpURL=');
				}
			}else{
				//验签失败
				//返回失败信息
				die('RespCode=9999|JumpURL=');
			}
		}	
	}

}
